package diona.model

import net.liftweb.record.{MetaMegaProtoUser, MegaProtoUser}
import xml.Elem
import net.liftweb.squerylrecord.RecordTypeMode._
import net.liftweb.record.field.LongField
import net.liftweb.http.RequestVar
import net.liftweb.common.Box
import org.squeryl.KeyedEntity
/**
 * User: anton
 * Date: 07.03.11 16:40
 */

class User extends MegaProtoUser[User] with KeyedEntity[LongField[User]]
{

  //lazy val images = PublisherSchema.userToImages.left(this)

  override def meta = User

  override lazy val password = new MyPassword(this)
  {
    override def match_?(toTest: String): Boolean =
      get == toTest

    override def set_!(in: Box[String]): Box[String] =
    {
      super.set_!(in)
      in.map(s => s)
    }
  }

  override def valUnique(errorMsg: => String)(email: String) = Nil
}

object CurrentUser extends RequestVar[User](null)

object User extends User with MetaMegaProtoUser[User]
{
  @volatile var byEmail: (String) => Option[User] =
    (email) => inTransaction {PublisherSchema.users.where(_.email === email).headOption}

  @volatile var byId: (Long) => Option[User] =
    (id) => inTransaction {PublisherSchema.users.where(_.id === id).headOption}

  override def typeToBridge(in: TheUserType): UserBridge = new MySquerylUserBridge(in)

  protected class MySquerylUserBridge(in: TheUserType) extends MyUserBridge(in)
  {
    override def save(): Boolean =
    {
      inTransaction {PublisherSchema.users.insertOrUpdate(in)}
      true
    }
  }

  protected def userFromStringId(id: String) =
  {
    byId(id.toLong)
  }

  protected def findUserByUniqueId(id: String) =
  {
    byId(id.toLong)
  }

  protected def findUserByUserName(email: String) =
  {
    byEmail(email)
  }

  def surroundXhtml(el: Elem): Elem =
  {
    <div id="main" class="lift:surround?with=default;at=content">
      {el}
    </div>
  }

  override def loginXhtml = surroundXhtml(super.loginXhtml)

  override def signupXhtml(user: User) = surroundXhtml(super.signupXhtml(user))

  override def lostPasswordXhtml = surroundXhtml(super.lostPasswordXhtml)

  override def passwordResetXhtml = surroundXhtml(super.passwordResetXhtml)

  override def editXhtml(user: User) = surroundXhtml(super.editXhtml(user))

  override def changePasswordXhtml = surroundXhtml(super.changePasswordXhtml)

  override def skipEmailValidation = true

  override def signupFields: List[FieldPointerType] = List(email, password)
}